#include "NewLineEdit.h"

NewLineEdit::NewLineEdit(QWidget *parent) : QLineEdit(parent)
{
    // 创建左侧图标
    iconLabel = new QLabel(this);
    // 默认设置一个图标
    setLeftIcon(":/resource/svg/custom.svg");
    // 创建右侧按钮
    m_pConfirmButton = new QPushButton("Clear", this);
    m_pConfirmButton->setFixedSize(80, 40);
    m_pConfirmButton->setVisible(false);  // 初始时按钮不可见
    m_pConfirmButton->setStyleSheet(
        "QPushButton {"
        "   background-color: rgb(87, 205, 255);"
        "   color: white;"
        "   border-radius: 15px;"
        "   padding: 10px 20px;"
        "   font-size: 20px;"
        "   color: #ffffff;"
        "   font-family: '幼圆', 'SimSun';"  // 如果“幼圆”不可用，则使用宋体（SimSun）
        "}"
        "QPushButton:hover {"
        "   background-color: lightblue;"     // 鼠标悬停时背景颜色变为浅蓝色
        "}"
        "QPushButton:pressed {"
        "   background-color: #3CC5FF;"      // 按下时背景颜色变为深蓝色
        "   padding: 12px 22px;"               // 按钮按下时的内边距
        "}"
    );

    // 将按钮放置在 QLineEdit 的右侧
    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setSpacing(0);
    layout->setContentsMargins(40, 0, 20, 0);
    layout->addWidget(iconLabel, 0, Qt::AlignLeft);  // 左侧图标
    layout->addWidget(m_pConfirmButton, 0, Qt::AlignRight);
    layout->addWidget(this, 1);  // 保证 QLineEdit 本身占据大部分空间

    // 连接 textChanged 信号到自定义槽函数
    connect(this, &QLineEdit::textChanged, this, &NewLineEdit::onTextChanged);

    // 按钮点击时清空文本框
    connect(m_pConfirmButton, &QPushButton::clicked, this, &NewLineEdit::onBtnConfirmClicked);
}

void NewLineEdit::setButtonText(const QString &text)
{
    if (m_pConfirmButton)
    {
        m_pConfirmButton->setText(text);
    }
}

void NewLineEdit::setLeftIcon(const QString &iconPath)
{
    pixmap.load(iconPath);
    iconLabel->setPixmap(pixmap.scaled(20, 20, Qt::KeepAspectRatio));  // 设置图标大小为 20x20
}

void NewLineEdit::setIconSize(int width, int height)
{
    m_nHeight = height;
    m_nWidth = width;
    iconLabel->setPixmap(pixmap.scaled(m_nWidth, m_nHeight, Qt::KeepAspectRatio));  // 设置图标大小为 20x20
}

void NewLineEdit::onTextChanged(const QString &text)
{
    // 判断文本是否为空，若不为空则显示按钮，否则隐藏
    m_pConfirmButton->setVisible(!text.isEmpty());
}

void NewLineEdit::onBtnConfirmClicked()
{
    if(!text().isEmpty()){
        emit sigConfirm();
    }
}
